<?php

namespace App\Http\Controllers\admin;

use App\Model\UserModel;
use Illuminate\Http\Request;
use App\Model\AdminLogsModel;
use App\Model\UserWalletModel;
use App\Model\UserWalletLogModel;
use Illuminate\Support\Facades\DB;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Hash;
use Validator;


//主页
class UserController extends Controller
{
	// 用户列表
	public function index(Request $request)
	{
		//搜索条件
		$keywords = $request->input('keywords');//关键字
		$sub_phone = $request->input('sub_phone');//搜索手机号
		$sub_email = $request->input('sub_email');//搜索邮箱
		$sub_state = $request->input('sub_state');
		$sub_status = $request->input('sub_status');
		$month = $request->input('month');//时间


		$list = UserModel::where(function ($query) {
			//昵称
			if (request()->keywords) {
				$query->where('user', request()->keywords);
			}

			//手机号
			if(request()->sub_phone){
				$query->where('phone','like',"%".request()->sub_phone."%");
			}

			//邮箱
			if(request()->sub_email){
				$query->where('email','like',"%".request()->sub_email."%");
			}

			//云仓库状态
			if(request()->sub_state){
				$query->where('is_vip',request()->sub_state);
			}
			if(request()->sub_status){
				$query->where('state',request()->sub_status);
			}

			if (request()->month) {
				$month_arr = explode("~", request()->month);
				$mintime = $month_arr[0];
				$maxtime = $month_arr[1] . " 23:59:59";
				$query->whereBetween('created_at', [$mintime, $maxtime]);
			}
		})
			->orderBy('id', 'desc')
			->paginate(10);
		$pages = $request->input('page', 1);
		return view('admin.user.index')
			->with('keywords', $keywords)
			->with('month', $month)
			->with('session_id', session('admin_id'))
			->with('pages', $pages)
			->with('sub_phone', $sub_phone)
			->with('sub_email', $sub_email)
			->with('sub_state', $sub_state)
			->with('sub_status', $sub_status)
			->with('list', $list);
	}

	//更改用户状态
	public function up_state(Request $request, UserModel $auModel)
	{
		$state = $request->post('state');//状态
		$id = $request->post('id');

		// return returnJson(0,'操作频繁');
		$returnArr = $auModel->updateState($id, $state);
		return response()->json($returnArr);
	}

	// 团队体系
	public function team(Request $request)
	{
		$user = "";
		if ($request->user) {
			$where = array();
			if ($request->user) {
				$user = $request->user;
				$where['user'] = $user;
			}

			$id = $request->user;
			if (!$id) {
				$list = array();
				return view('admin.user.team', compact("list", "user"));
			}
			$sql = "SELECT DISTINCT a.id,a.pid,a.user,a.team,a.push,IF(b.id, 0, 1) is_parent FROM users a LEFT JOIN users b ON a.id = b.pid WHERE a.id = " . $id;
			$list = DB::select($sql);
		} else {
			if ($request->id) {
				$id = $request->id;
				$sql = "SELECT DISTINCT a.id,a.pid,a.user,a.team,a.push,IF(b.id, 0, 1) is_parent FROM users a LEFT JOIN users b ON a.id = b.pid WHERE a.id = " . $id;
				$list = DB::select($sql);
			} else {
				$sql = "SELECT DISTINCT a.id,a.pid,a.user,a.team,a.push,IF(b.id, 0, 1) is_parent FROM users a LEFT JOIN users b ON a.id = b.pid WHERE a.pid = 0";
				$list = DB::select($sql);
			}
		}
		foreach ($list as $key => $value) {
			$list[$key] = json_decode(json_encode($value), true);
		}
		// 浏览团队体系
		return view('admin.user.team', compact("list", "user"));
	}

	public function team_list(Request $request)
	{
		$id = $request->id;
		$sql = "SELECT DISTINCT a.id,a.pid,a.user,a.team,a.push,IF(b.id, 0, 1) is_parent FROM users a LEFT JOIN users b ON a.id = b.pid WHERE a.pid = " . $id;
		$list = DB::select($sql);
		foreach ($list as $key => $value) {
			$list[$key] = json_decode(json_encode($value), true);
		}
		return json_encode($list);
	}

	//资产调整
	public function account(Request $request)
	{
		$wallet_log = UserWalletLogModel::orderByRaw('created_at desc')->where('status', 1)->where(function ($query) {
			if (request()->keywords) {
				$uid = UserModel::where('user', request()->keywords)->value('id');
				$query->where('uid', $uid);
			}
		})->paginate(9);
		return view('admin.user.account', compact('wallet_log', 'request'));
	}

	//资产调整
	public function account_update(Request $request)
	{
		$post = $request->post();
		$validator = Validator::make($post, [
			'username' => 'required|exists:users,user',
			'type' => 'required|digits_between:1,6',
			'sign' => 'required|digits_between:1,2',
			'num' => 'required',
		], [
			'username.required' => '请输入账号',
			'username.exists' => '账号不存在',
			'type.required' => '请选择资产类别',
			'num.required' => '请输入金额'
		]);
		if ($validator->fails()) {
			return returnJson(0, $validator->errors()->first());
		}

		$uid = UserModel::where('user', request()->username)->value('id');
		if (request()->type == 1) {
			$str = 'money';
			$str_cy = '现金资产';
		} elseif (request()->type == 2) {
			$str = 'lock_money';
			$str_cy = '货款资产';
		} else {
			return returnJson(0, '资产类别不存在');
		}
		if (request()->num <= 0) {
			return returnJson(0, '请输入有效数字');
		}
		$account = UserWalletModel::where('uid', $uid)->first();
		DB::beginTransaction();
		try {
			if (request()->sign == '1') {
				$sign_cy = '+';
				UserWalletModel::handleAccount($uid, request()->num, '+', '后台添加资产', request()->type, 1);


			} elseif (request()->sign == '2') {
				$sign_cy = '-';
				if (request()->num > UserWalletModel::where('uid', $uid)->value($str)) {
					return returnJson(1, '可扣余额不足');
				}
				UserWalletModel::handleAccount($uid, request()->num, '-', '后台扣除资产', request()->type, 1);
			}
			$msg = '用户【' . request()->username . '】(id:' . $uid . '):' . $str_cy . $sign_cy . request()->num;
			AdminLogsModel::addLog($msg);
			DB::commit();
			return returnJson(1, '添加成功');
		} catch (Expectation $e) {
			DB::rollback();
			return returnJson(0, '添加失败');
		}
	}

	//资产日志
	public function account_log(Request $request)
	{
		$wallet_log = UserWalletLogModel::orderByRaw('created_at desc')->where(function ($query) {
			if (request()->keywords) {
				$uid = UserModel::where('user', request()->keywords)->value('id');
				$query->where('uid', $uid);
			}
			if(request()->sub_type){
				$query->where('type',request()->sub_type);
			}
			if(request()->sub_status){
				$query->where('status',request()->sub_status);
			}
			if (request()->month) {
				$month_arr = explode("~", request()->month);
				$mintime = $month_arr[0];
				$maxtime = $month_arr[1] . " 23:59:59";
				$query->whereBetween('created_at', [$mintime, $maxtime]);
			}
		})->paginate(10);

		$page = $wallet_log->links();
		return view('admin.user.account_log', compact('wallet_log', 'request', 'page'));
	}

	public function user_create(Request $request)
	{
		return view('admin.user.add_user', compact('request'));
	}

	public function user_store(Request $request)
	{
		//type 1手机号 2邮箱
		$phone = '';
		$email = '';
		$str_phone = '/^[1]\\d{10}$/';
		$str_email = '/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/';
		if (request()->login_type == 1) {
			if (!preg_match($str_phone, request()->username)) {
				return ['code' => 0, 'msg' => retStrInfo(4)];
			}
			$user = UserModel::where('phone', request()->username)->first();
			$phone = request()->username;
		} else {
			if (!preg_match($str_email, request()->username)) {
				return ['code' => 0, 'msg' => retStrInfo(5)];
			}
			$user = UserModel::where('email', request()->username)->first();
			$email = request()->username;
		}
		//账号是否存在
		if ($user) {
			return ['code' => 0, 'msg' => retStrInfo(6)];
		}

		$post = $request->post();
		$validator = Validator::make($post, [
			'username' => 'required',
			'user' => 'required',
//			'invite_code' => 'required',
			'password' => 'required|regex:/^\\d{6}$/',
			'paypass' => 'required|regex:/^\\d{6}$/',
		], [
			'username.required' => '请输入账号',
			'user.required' => '请输入昵称',
//			'invite_code.required' => '请输入邀请码',
			'password.required' => '请输入登陆密码',
			'password.regex' => '登陆密码格式错误',
			'paypass.required' => '请输入二级密码',
			'paypass.regex' => '二级密码请输入6位数字',
		]);
		if ($validator->fails()) {
			return returnJson(0, $validator->errors()->first());
		}

		//云仓号
		$pid = 0;
		$path = '0,';
		if (request()->invite_code) {
			$puser = UserModel::where('invite_code', request()->invite_code)->where('level', 2)->first();
			if (!$puser) {
				return ['code' => 0, 'msg' => retStrInfo(1)];
			}
			$pid = $puser['id'];
			$path = $puser['path'] . $pid . ",";

		}
		//昵称
		if (!request()->user) {
			return ['code' => 0, 'msg' => retStrInfo(2)];
		}
		$str_user = '/^[a-zA-Z]{1,15}$/';
		if (!preg_match($str_user, request()->user)) {
			return ['code' => 0, 'msg' => retStrInfo(120)];
		}
		if (UserModel::where('user', request()->user)->first()) {
			return ['code' => 0, 'msg' => retStrInfo(3)];
		}
		if (UserModel::where('user', request()->user)->first()) {
			return ['code' => 0, 'msg' => retStrInfo(3)];
		}

		DB::beginTransaction();
		try {
			if (request()->invite_code) {
				$pids = explode(',', $path);
				foreach ($pids as $k => $v) {
					UserModel::where('id', $v)->increment('team');
				}
				UserModel::where('id', $pid)->increment('push');
			}
			do {
				$invite_code = getRandomString(6);
			} while (UserModel::where('invite_code', $invite_code)->first());

			$auth_name = "/^[\x{4e00}-\x{9fa5}]{2,6}$/u";
			if (preg_match($auth_name, request()->user)) {
				$pin = app('pinyin');
				$pinyin = $pin->abbr(request()->user);
			} else {
				$pinyin = request()->user;
			}
			//首字母
			$head = pinying($pinyin);

			$user = UserModel::create([
				'phone' => $phone,
				'email' => $email,
				'password' => Hash::make(request()->password),
				'paypass' => Hash::make(request()->paypass),
				'pid' => $pid,
				'path' => $path,
				'user' => request()->user,
				'invite_code' => $invite_code,
				'login_type' => request()->login_type,
				'head' => $head,
			]);
			$user->generateToken();
			UserWalletModel::create([
				'uid' => $user->id,
			]);

			$qrCode = new \Endroid\QrCode\QrCode('http://' . request()->getHost() . '/invite_own?invite=' . $user['invite_code']);

			$qrCode->setSize(300);
			$qrCode->writeFile(public_path() . "/upload/invite/{$user['id']}.png");
			$bigImgPath = public_path() . '/upload/invite/invite.png';
			$qCodePath = public_path() . "/upload/invite/{$user['id']}.png";
			$bigImg = imagecreatefromstring(file_get_contents($bigImgPath));
			$qCodeImg = imagecreatefromstring(file_get_contents($qCodePath));
			list($qCodeWidth, $qCodeHight, $qCodeType) = getimagesize($qCodePath);
			imagecopymerge($bigImg, $qCodeImg, 150, 50, 0, 0, $qCodeWidth, $qCodeHight, 100);
			list($bigWidth, $bigHight, $bigType) = getimagesize($bigImgPath);
			$textcolor = imagecolorallocate($bigImg, 255, 140, 25);
			imagettftext($bigImg, 40, 0, 248, 550, $textcolor, public_path() . '/myfont.ttf', $v['invite_code']);
			imagepng($bigImg, public_path() . "/upload/invite/{$user['id']}.png");

			$msg = '添加用户【' . request()->user . '】(id:' . $user->id . ')';
			AdminLogsModel::addLog($msg);
			DB::commit();
			return ['code' => 1, 'msg' => '添加成功'];
		} catch (Expectation $e) {
			DB::rollback();
			return ['code' => 0, 'msg' => '添加失败'];
		}
	}


}
